%%%-------------------------------------------------------------------
%%% @author admin
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 30. 十二月 2021 15:21
%%%-------------------------------------------------------------------
-module(unpack).
-author("admin").
-behaviour(unpack_behav).
-include("log.hrl").

%% API
-export([unpack/1]).


unpack(Bin) ->
  unpack(Bin, []).

unpack(<<>>, Acc) -> {ok, lists:reverse(Acc), <<>>};
unpack(<<Len:16,MsgId:16, BinData:Len/binary, Res/binary>>, Acc) ->
  Pb_Mod = msg_rec_reflect:pb_mod(MsgId div 1000),
  RecName = msg_rec_reflect:rec_name(MsgId),
  NewAcc = try
             Tuple = Pb_Mod:decode_msg(BinData, RecName),
             [{MsgId, Tuple}|Acc]
           catch
             _Err:_Reason  ->
               ?ERR(" error msgid:~w, reason:~w",[MsgId,{_Err, _Reason}]),
               Acc
           end,
  unpack(Res, NewAcc);
%%  case string_to_term(unicode:characters_to_list(Msg, utf8)) of
%%    {ok, Term} ->
%%      case term_to_record(MsgId, Term) of
%%        error -> unpack(Res, Acc);
%%        Tuple -> unpack(Res, [{MsgId, Tuple}|Acc])
%%      end;
%%    _ -> unpack(Res, Acc)
%%  end;
%% todo 此处可以处理连续包组成的大包。不过这里就不处理了
%%unpack(Res, Acc) -> {error, lists:reverse(Acc), Res}.
unpack(_Res, _Acc) -> error.




%%string_to_term(String) ->
%%  case erl_scan:string(String++".") of
%%    {ok, Tokens, _} ->
%%      case erl_parse:parse_term(Tokens) of
%%        {ok, Term} -> {ok, Term};
%%        _Err -> undefined
%%      end;
%%    _Error ->
%%      undefined
%%  end.
%%
%%
%%term_to_record(MsgId, Term) ->
%%  case msg_rec_reflect:rec_name(MsgId) of
%%    undef ->
%%      ?ERR(" error msgid:~w",[MsgId]),
%%      error;
%%    RecName -> list_to_tuple([RecName|Term])
%%  end.

